﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace JYJ.AiYard.StationManagement.YardCommonHald
{
    public static class MD5
    {
        #region 用MD5加密字符串 可选择生成16位或者32位的加密字符串
        /// <summary>
        /// 用MD5加密字符串，可选择生成16位或者32位的加密字符串
        /// </summary>
        /// <param name="Text">待加密的字符串</param>
        /// <param name="bit">位数，一般取值16 或 32</param>
        /// <returns>返回的加密后的字符串</returns>
        public static string MD5Encrypt(string Text, int bit)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] hashedDataBytes;
            hashedDataBytes = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(Text));
            StringBuilder tmp = new StringBuilder();
            foreach (byte i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }
            if (bit == 16)
            {
                return tmp.ToString().Substring(8, 16);
            }
            else
            if (bit == 32)
            {
                return tmp.ToString();
            }//默认情况
            else
            {
                return string.Empty;
            }
        }
        #endregion

        #region 用MD5加密字符串
        /// <summary>
        /// 用MD5加密字符串
        /// </summary>
        /// <param name="Text">待加密的字符串</param>
        /// <returns></returns>
        public static string MD5Encrypt(string Text)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] hashedDataBytes;
            hashedDataBytes = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(Text));
            StringBuilder tmp = new StringBuilder();
            foreach (byte i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }
            return tmp.ToString();
        }
        #endregion
    }
}
